import { defineStore } from 'pinia';
import { isEmpty } from 'lodash-es';
import { useAutoAction, useAutoGetter } from './autoActionGetter.js';
import { handleCommonRes } from '../utils/resolver.js';
import { getAreaTreeList, getSystemTree, getUnitTree } from '../api/index.js';
import { getAreaCode, getAreaLevel } from './areaCode.js';
import { getStoreId } from './utils.js';

const id = getStoreId('TreeDataStore');
export const useTreeDataStore = defineStore(id, {
  state: () => ({
    areaTreeReplaceFields: { children: 'nodes', title: 'text', key: 'code' },
    unitTreeReplaceFields: { children: 'nodes', title: 'text', key: 'code' },
    systemTreeReplaceFields: { children: 'nodes', title: 'text', key: 'code' },
    areaTreeStore: {},
    unitTreeStore: {},
    systemTree: [],
  }),
  getters: {
    getAreaTree: useAutoGetter({
      getter: (state) => (level) => {
        level = getAreaLevel(level);
        return state.areaTreeStore[level];
      },
      action: async function (params) {
        await this.getAreaTreeAsync(params);
      },
    }),
    getUnitTree: useAutoGetter({
      getter: (state) => (params) => {
        const area_code = getAreaCode(params);
        return state.unitTreeStore[area_code];
      },
      action: async function (params) {
        await this.getUnitTreeAsync(params);
      },
    }),
  },
  actions: {
    clearTree() {
      this.$reset();
    },
    getAreaTreeAsync: useAutoAction({
      action: async function (level) {
        level = getAreaLevel(level);
        if (!isEmpty(this.areaTreeStore[level])) {
          return this.areaTreeStore[level];
        }
        const params = { max_level: level };
        const data = await handleCommonRes(getAreaTreeList, params);
        this.areaTreeStore[level] = data;
        return data;
      },
    }),
    getUnitTreeAsync: useAutoAction({
      action: async function (params) {
        let area_code = getAreaCode(params);
        if (!isEmpty(this.unitTreeStore[area_code])) {
          return this.unitTreeStore[area_code];
        }
        params = Object.assign({ area_code, is_contain_oneself: false }, params);
        const data = await handleCommonRes(getUnitTree, params);
        this.unitTreeStore[area_code] = data;
        return data;
      },
    }),
    async getSystemTreeAsync() {
      if (!isEmpty(this.systemTree)) {
        return this.systemTree;
      }
      this.systemTree = await handleCommonRes(getSystemTree, {});
      return this.systemTree;
    },
  },
});
